//
//  UUPushManager.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 03/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUPushManager.h"
#import <UserNotifications/UserNotifications.h>
#import <JPush/JPUSHService.h>
#import "AppDelegate.h"
#import <UUFoundation/DKDeviceInfo.h>

#import "UUUserManager.h"
#import "UUKeeperManager.h"
#import "UUFleetManager.h"
#import "UULoginManager.h"

@interface UUPushManager () <JPUSHRegisterDelegate, UUKeeperManagerObserver>

@property (nonatomic, copy, readwrite) NSString *tokenString;

@end

@implementation UUPushManager

- (instancetype)initWithLaunchOptions:(NSDictionary *)launchOptions {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)registerPush {
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:nil
                           appKey:JPUSH_APP_KEY
                          channel:nil
                 apsForProduction:
#ifdef RUNNING_ACTIVE_MODE
     NO
#else
     YES
#endif
     ];
    
    [JPUSHService setAlias:GetDeviceInfo().uuid completion:nil seq:0];
    [self updateTags];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_didReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
    
    [GetKeeperManager() addObserver:self];
}

- (void)unregisterNotifications {
    [JPUSHService cleanTags:nil seq:0];
    [JPUSHService deleteAlias:nil seq:0];
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)registerDeviceWithToken:(NSData *)token {
    NSString *tokenString = [[[[token description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                              stringByReplacingOccurrencesOfString: @">" withString: @""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    
    self.tokenString = tokenString;
    DKLog(@"device token: %@\n%@", tokenString, token);
    
    [JPUSHService registerDeviceToken:token];
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)_didReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    
    NSDictionary *message = [userInfo valueForKey:@"extras"];
    [GetAppDelegate() receiveMessage:message];
}

- (void)updateTags {
    UUUserInfo *userInfo = GetUserManager().fetchUserInfo;
    
    NSMutableSet *tags = [NSMutableSet setWithObjects:
                          [NSString stringWithFormat:@"vendor_%@", userInfo.supplierId],
                          [NSString stringWithFormat:@"role_%ld", userInfo.roleId],
                          @"platform_2",
                          [NSString stringWithFormat:@"uid_%@", userInfo.userId],
                          [NSString stringWithFormat:@"vendorCityId_%@", userInfo.cityId],
                          nil];
    
    UUKeeperModel *keeper = [GetKeeperManager() fetchKeeperWithKeeperId:userInfo.userId];
    if (keeper) {
        NSArray<NSString *> *fleetIds = [keeper.fleetIds componentsSeparatedByString:@","];
        for (NSString *fleetId in fleetIds) {
            UUFleetModel *fleet = [GetFleetManager() fetchFleetWithFleetId:fleetId];
            if (fleet && fleet.districtIds) {
                NSArray<NSString *> *districts = [fleet.districtIds componentsSeparatedByString:@","];
                for (NSString *district in districts) {
                    [tags addObject:[NSString stringWithFormat:@"cityId_%@", district]];
                }
            }
        }
    }
    
    [JPUSHService setTags:tags completion:nil seq:0];
}

#pragma mark - JPUSHRegisterDelegate methods

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler NS_AVAILABLE_IOS(10_0) {
    NSDictionary *userInfo = notification.request.content.userInfo;
    [GetAppDelegate() receiveMessage:userInfo];
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmismatched-parameter-types"

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler NS_AVAILABLE_IOS(10_0) {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    
    completionHandler();  // 系统要求执行这个方法
}

#pragma clang diagnostic pop

#pragma mark - UUKeeperManagerObserver methods

- (void)keeperManagerDidupdateCurrentUser {
    [self updateTags];
}

@end
